import { isWeibo, replaceStr, isJSON } from '@/plugins/utils'
import { H5_TYPE } from '@/common/const-dif'
import { EventBus } from '@/store/index'
import { getMainWbDataEventByEvents } from '@/store/utils'
import { mapState, mapActions } from 'vuex'
import { COMPONENT_TYPES, PAGE_TYPE, EVENTS_RESULTS_TYPES_MAP, CONTROL_TYPES } from '@/common/const'
import { GENERAL_TYPES_MAP } from '@/common/const-general'
import { EVENT_HOVER_TYPES, FRONT_EVENTS } from '@/common/events'
import { getMousePos, isHasOwnProperty, getCompIdByParam } from '@/plugins/utils'
import { API_VERSION, postStatics } from '@/service/statics'

import axios_ from '@/utils/axios'
import { Toast } from 'vant'
import OpenPushEvent from '@/components/events/OpenPushEvent'
import PushEvent from '@/components/events/PushEvent'
import FollowEvent from '@/components/events/FollowEvent'
import CompareInCompsEvent from '@/components/events/CompareInCompsEvent'
import Rotate3dEvent from '@/components/events/Rotate3dEvent'
import InteractionEvent from '@/components/events/InteractionEvent'
import InteractionDataEvent from '@/components/events/InteractionDataEvent'
import SaveImgEvent from '@/components/events/SaveImgEvent'
import ShowOrHiddenEvent from '@/components/events/ShowOrHiddenEvent'
import ShakeEvent from '@/components/events/ShakeEvent'
import GeneralEvent from '@/components/events/GeneralEvent'

const LOTTERY_ERROR_NOS = [920105, 920106, 920107, 920109, 920110, 920111, 920112, 920113,
  920114, 920115, 920116, 920117, 920118, 900104]

export const wbBase = {
  data () {
    return {
      initEvents: [],
      loadEvents: [],
      wbEvents: [],
      wbTypes: [],
      commonFrontEvents: [],
      commonEvents: [],
    }
  },
  props: {
    item: Object,
  },
  created () {
    const data_ = {
      isApiSended: {},
      eventIndex: 0,
      isPost: true,
      isClick: true,
      isEventPostFail: false,//一个事件返回失败的变量，用来做下一个事件的判断条件，发博成功与失败不同文案
    };
    for(let key in data_) {
      this[key] = data_[key];
    }
  },
  computed: {
    ...mapState({
      allPages: state => state.allPages ? state.allPages : state.components.pages,
      controls: state => state.controls ? state.controls : state.wbComponents.controls,
      componentMap: state => state.componentMap ? state.componentMap : state.components.componentMap,
      canvasImgComponentMap: state => state.canvasImgComponentMap,
      pages: state => state.pages,
      pops: state => state.pops_,
      menuComponent: state => state.menuComponent,
      pageIndex: state => state.pageIndex,
      statePopId: state => state.popId,
      siteAttrs: state => state.attrs,
      shareData: state => state.shareData,
      interactionData: state => state.interactionData,
      fileUploadData: state => state.fileUploadData,
      fixedComps: state => state.fixedComps,
      formValues: state => state.formValues,
      frontSelectScoreFormValues: state => state.frontSelectScoreFormValues,
      activityInfo: state => state.activityInfo,
      globalIsPost: state => state.globalIsPost,
      siteInfo: state => state.siteInfo,
      userInfo: state => state.userInfo,
      frontData: state => state.frontData,
      push_visible: state => state.attrs.push_visible,
      isGlobalShareComponents: state => state.isGlobalShareComponents,
      appid: state => state.attrs.wb_appkey,
      isLoadJsObj: state => state.isLoadJsObj,
      animates: state => state.animates,
      timeObj: state => state.timeObj,
      isForm: state => state.isForm,
    }),
    getItemControls(){
      if(this.isH5Edit) {
        return this.controls[this.item.id]
      }else{
        if(this.item){
          return this.controls[this.item.id]
        }else{
          return this.controls[this.currentPage.id]
        }
      }
    },
  },
  methods: {
    ...mapActions({
      updateActivityInfo: "updateActivityInfo",
      updateComponentAttr: "updateComponentAttr",
      updateControls: "updateControls",
    }),
    resetSubmitStatus() {
      this.eventIndex = 0
      this.isPost = true
      this.isClick = true
    },
    onPostStatics(e, { comType, wModule, jumpUrl, params, apiUri }) {
      if (this.isH5Edit) {
        return
      }
      let xy = getMousePos(e)
      let comId
      if (this.item) {
        comId = this.item.id
      } else {
        comType = 'pageOrPop'
        comId = "pageId: " + this.pageId + "popId: " + this.popId
      }
      postStatics(this.$store.state, {
        comType, comId, wModule, pageIndex: this.pageIndex, apiType: "",
        apiUri: apiUri ? apiUri : "", params: params ? params : "", jumpUrl, clickSequence: "", mouseX: xy.x, mouseY: xy.y
      })
    },
    onEvent(e) {
      if (this.isH5Edit || !this.isClick) {
        return
      }
      // if(!this.siteInfo.md.isMobile && isHasOwnProperty(this.siteAttrs, "isPcInteraction") && !this.siteAttrs.isPcInteraction) {
      //   this.showToast('亲，请扫描旁边的二维码在移动端查看哦！')
      //   return
      // }
      if (this.commonFrontEvents.length > 0) {
        this.isClick = false
        this.onFrontEvents(e, this.commonFrontEvents)
      } else if (this.wbEvents.length > 0 && this.wbEvents[this.eventIndex]) {
        if (this.siteInfo.isTemplate) {
          this.showToast('亲，模板只供查看页面哦！！！')
          this.resetSubmitStatus()
          return
        }
        if (this.siteAttrs.isOffline) {
          this.showToast('亲，活动已下线了哦！！！')
          this.resetSubmitStatus()
          return
        }
        //倒计时提示
        // if (this.wbTime < 0) {
        //   this.showToast("活动还未开始！！请耐心等待")
        //   return
        // }
        this.isPost = false
        this.isClick = false
        this.postWbEvent({ e })
      } else {
        this.isClick = false
        if(this.commonEvents.length <= 0) {
          const eventAttr = this.item.eventAttr
          if(eventAttr && isHasOwnProperty(eventAttr, "isEmitInitEvent") && eventAttr.isEmitInitEvent) {
            EventBus.$emit("reloadInit", { pageId: this.pageIndex+1 })
          }
          this.resetSubmitStatus()
        } else {
          this.onFrontEvents(e)
        }
      }
    },
    showPop(popId) {
      if(!this.pops[popId-1]){
        return
      }
      if (this.statePopId > 0 && this.statePopId != popId) {
        EventBus.$emit('closePop')
      }
      this.$store.commit('updatePopId', { popId })
      EventBus.$emit("showPop", { popId })
    },
    showPage(pageId) {
      if(!this.pages[pageId-1]){
        return
      }
      if (this.statePopId > 0) {
        EventBus.$emit('closePop')
      }

      EventBus.$emit("isStartHtml2canvas", { isStart: true, compId: this.item.id});
      let pageIndex = pageId - 1
      this.$store.commit('updatePageIndex', { pageIndex })

      EventBus.$emit('pauseVideo', { pageId })
      EventBus.$emit('playOrPauseAudio', { isPlay: false })
      if (this.siteAttrs.h5Type == H5_TYPE.mobile && !this.siteAttrs.isNoSwiping && this.siteAttrs.pageType == PAGE_TYPE.single) {
        EventBus.$emit("swiper", { pageId })
      } else {
        EventBus.$emit('showPage', { pageId })
      }
      this.$nextTick(() => {
        EventBus.$emit("isStartHtml2canvas", { isStart: false, compId: this.item.id});
      })
    },
    isPostWbEventOrCommonEvents({ loadEvent, e }){
      let event = loadEvent ? loadEvent : this.wbEvents[this.eventIndex]
      if(event){
        this.postWbEvent({ loadEvent, e })
      }else{
        this.onFrontEvents(e)
      }
    },
    postWbEvent({ loadEvent, e }) {
      let event = loadEvent ? loadEvent : this.wbEvents[this.eventIndex]
      let url
      let controlId = event.controlId
      let params = { com_id: this.item.id, type: event.type, mouseBehavior: event.mouseBehavior, controlId, e: e }
      let controlData
      if (this.getItemControls) {
        controlData = this.getItemControls[controlId]
      }
      if (event.type == EVENT_HOVER_TYPES.smsVerification.type) {
        let relateCompId = getCompIdByParam(event.comps[0].attrs.value)
        if (relateCompId) {
          this.eventIndex++;
          let phone = this.formValues[relateCompId] ? this.formValues[relateCompId].value : ''
          if (/^1[3-5789]\d{9}$/.test(phone)) {
            this.post("/sms/", { phone, e })
            let msg = "验证码已发，请注意查看手机"
            this.showToast(msg);
          } else {
            this.resetSubmitStatus()
            let msg = "电话号码输入不正确"
            this.showToast(msg);
          }
          return
        }
      } else if (event.type == EVENT_HOVER_TYPES.submit.type) {
        //提交过表单 表单提示的时候有次数限制时提示信息
        if(this.item.events.activityInfo){
          if(this.activityInfo.num_form > 0 && controlData.data.day_limit > 0){
            this.postShowPop({isSuccess: false, item: this.item, eventAttr: this.item.eventAttr, type: this.item.events.activityInfo.type, data: {msg: "", code: 900104}})
            this.resetSubmitStatus();
            return
          }
        }
        this.eventIndex++
        EventBus.$emit('wbsubmit', { e, item: this.item })
        return
      }else if (event.type == EVENT_HOVER_TYPES.number.type) {
        if(controlData.data.onceGrowValue != 0){
          if(controlData.data.onceGrowValue < 0){
            if(controlData.data.syn_com_id){
              let synCompId = getCompIdByParam(controlData.data.syn_com_id);
              let symControlData = synCompId && this.controls[synCompId][event.controlId];
              if(symControlData && symControlData.data.num > 0){
                url = '/feact/number'
              }
            }else {
              if(controlData.data.num > 0){
                url = '/feact/number'
              }
            }
          }else{
            url = '/feact/number'
          }
          //链接带过来的uid
          if (this.siteInfo.from && this.siteInfo.from.length > 0) {
            _.merge(params, { from: this.siteInfo.from })
          }
          //更新计数每次增加数据 2152
          if(controlData.data.isDynamic) {
            _.merge(params, { onceGrowValue: controlData.data.onceGrowValue, vipOnceGrowValue: controlData.data.vipOnceGrowValue })
          }
          //关联触发计数组件id
          let syn_com_id = getCompIdByParam(controlData.data.syn_com_id)
          if (syn_com_id && syn_com_id.length > 0) {
            let synComData = this.componentMap[syn_com_id];
            if(synComData && synComData.events.number) {
              _.merge(params, { syn_com_id })
            }
          }
        }
      } else if (event.type == EVENT_HOVER_TYPES.vote.type) {
        url = '/feact/vote';
        let vote_id = '';
        if (this.isWbLists) {
          let voteItem = this.wbLists[this.commonAttr.itemIndex];
          vote_id = voteItem.voteId || voteItem.mid || voteItem.uid
          this.item.commonAttr.pushIndex = voteItem.voteId - 1
          //存储link 在事件网页跳转中使用,
          if(voteItem.mid){
            let midJump = "sinaweibo://detail/?mblogid=" + voteItem.mid;
            let shareData = { link: voteItem.link, midJump };
            this.$store.commit('updateShareData', shareData);
          }
        } else if(this.lists && this.lists.length > 0){
          vote_id = this.item.commonAttr.voteId || this.item.lists[this.commonAttr.itemIndex].voteId;
          this.item.commonAttr.pushIndex = vote_id - 1;
        } else {
          vote_id = this.item.commonAttr.voteId ? this.item.commonAttr.voteId : 1;//非list组件添加投票组件，设置投票id为1
          this.item.commonAttr.pushIndex = vote_id - 1;
        }
        let syn_com_id = getCompIdByParam(controlData.data.syn_com_id);
          if (syn_com_id && syn_com_id.length > 0) {
            _.merge(params, { syn_com_id })

            let syn_vote_ids = controlData.data.syn_vote_ids;
            syn_vote_ids = _.trim(syn_vote_ids);
            if (syn_vote_ids.length > 0) {
              if (syn_vote_ids.split(",").length > 0) {
                _.merge(params, { syn_vote_ids })
              }
            }
          }
        _.merge(params, { vote_id })
      } else if (event.type == EVENT_HOVER_TYPES.push.type) {
        //1、不需要控制全局发博 2、需要控制全局发博
        if(isHasOwnProperty(this.globalIsPost, 'isPush') && !this.globalIsPost.isPushClickObj[this.item.id]) {
          //不发博继续后面的事件
          url = ''
        } else {
          let pushEvent = new PushEvent();
          let { text, pic_ids, url_, isContinue } = pushEvent.excute({item:this.item, event, isEventPostFail: this.isEventPostFail});
          if(!isContinue){
            this.resetSubmitStatus();
            return
          }
          url = url_
          _.merge(params, { text, pic_ids })
        }
      } else if (event.type == EVENT_HOVER_TYPES.repost.type) {
        let elements = controlData.data.elements
        let index = _.random(0, elements.length - 1)
        let mid = controlData.data.mid
        if(this.commonAttr.itemIndex >= 0){
          let repostsData = this.getItemControls[CONTROL_TYPES.wb_reposts]
          if (repostsData) {
            let repostItem = repostsData.data.elements[this.commonAttr.itemIndex]
            if (repostItem) {
              mid = repostItem.mid
            }
          }
        }
        let text = elements[index].text ? elements[index].text : ''
        if (mid && mid.length > 0) {
          url = '/feact/wb_repost'
          _.merge(params, { mid, text })
        }
      } else if (event.type == EVENT_HOVER_TYPES.follow.type) {
        let followEvent = new FollowEvent();
        let { followUrl, follow_uid } = followEvent.excute({item: this.item, event, controlData});
        url = followUrl;
        _.merge(params, { follow_uid });
        followEvent.destroy();
      } else if (event.type == EVENT_HOVER_TYPES.praise.type) {
        url = '/feact/wb_praise'
        _.merge(params, { mid: controlData.data.mid })
      } else if (event.type == EVENT_HOVER_TYPES.lottery.type) {
        url = '/feact/lottery'
      } else if (event.type == EVENT_HOVER_TYPES.msg.type) {
        url = '/feact/wb_msg'
        let index = _.random(0, controlData.data.elements.length - 1)
        let text = replaceStr(this.formValues, controlData.data.elements[index])
        let send_uid = controlData.data.send_uid
        let rec_uid = ''
        // 关联组件获取uid
        let relateCompId = getCompIdByParam(controlData.data.rec_uid)
        if (relateCompId) {
          if (this.formValues[relateCompId] && this.formValues[relateCompId].item) {
            rec_uid = this.formValues[relateCompId].item.uid || this.formValues[relateCompId].item.id
          }
        } else {
          rec_uid = this.userInfo.uid
        }
        _.merge(params, { send_uid, rec_uid, text })
      } else if (event.type == EVENT_HOVER_TYPES.packet.type) {
        url = '/feact/wb_packet'
        params.from = useSite.siteInfo.wbFrom
        params.aid = useSite.siteInfo.wbAid
      } else if (event.type == EVENT_HOVER_TYPES.general.type) {
        url = '/feact/general'
        let isContinue = true
        let generalEvent = new GeneralEvent();
        let { url_, isContinue_ } = generalEvent.excute({item: this.item, event, params, eventResultDisplay: this.eventResultDisplay});
        url = url_;
        isContinue = isContinue_;
        generalEvent.destroy();
        if(!isContinue){
          this.resetSubmitStatus();
          return
        }
      } else if (event.type == EVENT_HOVER_TYPES.judgeRightWrong.type) {
        url = '/feact/general'
        let ele_key = controlData.data.ele_key
        if (ele_key == GENERAL_TYPES_MAP.activity) {
          params.ele_key = controlData.data.ele_key;  // activity
        }
      } else if (event.type == EVENT_HOVER_TYPES.activityInfo.type) {
        let activityType = controlData.data.activityType;

        let pageId = controlData.data.jumpPageId && parseInt(controlData.data.jumpPageId)
        let popId = controlData.data.jumpPopId && parseInt(controlData.data.jumpPopId)

        if(activityType == GENERAL_TYPES_MAP.lotteryForm) {
          if(controlData.data.isPopup){
            if (pageId > 0) {
              controlData.data.isPopup = false
              this.showPage(pageId)
              this.$store.commit('updateLotteryForm', {id: this.item.id, controlId: controlData.controlId, data: {isPopup: false}});
            }
            if(popId > 0){
              this.$store.commit('updateLotteryForm', {id: this.item.id, controlId: controlData.controlId, data: {isPopup: false}});
              this.showPop(popId)
            }
            this.resetSubmitStatus()
            return
          }
        }else{
          //全局数据在获取到数据没有设置pages的时候就初始化了的 参加过活动后就不能在参与活动了，不需要提交数据，流程正常走
          //这个没有 触发事件
          if(activityType != GENERAL_TYPES_MAP.scoreForm){
            url = '/feact/general'
          }
          let hint;
          if(this.activityInfo.isJoin) {
            hint = "亲，您已经参加过这个活动了！！";
            let hintStr = event.comps[0].attrs.value;
            if(hintStr && isJSON(hintStr)){
              let hintObj = JSON.parse(hintStr);
              if(hintObj.hint || hintObj.hint == ''){
                hint = hintObj.hint;
              }
            }
          }else{
            this.updateActivityInfo({ id: '', controlId: '', data: { isJoin: true } })
          }
          _.merge(params, { ele_key: activityType })//tree
          if (pageId > 0) {
            this.showPage(pageId)
          }
          if(popId > 0){
            this.showPop(popId)
          }
          if(hint){
            this.showToast(hint)
          }
        }
      }
      if (url) {
        this.post(url, params)
      }else{
        this.eventIndex++;
        this.isPostWbEventOrCommonEvents({loadEvent:null, e:null})
      }
    },
    compareInCompsIsContinue(compareCompData, numberControlData, numberMinusControlData){
      let isContinue = true;
      if (numberMinusControlData && numberControlData && numberControlData.data.isUid) {
        if(numberMinusControlData.data.onceGrowValue < 0 || numberMinusControlData.data.op == '-'){
          let event = getMainWbDataEventByEvents(compareCompData.events);
          const num = parseInt(numberControlData.data.num);
          const onceGrowValue = parseInt(numberMinusControlData.data.onceGrowValue);
          if (num - Math.abs(onceGrowValue) < 0) {
            let errorStr = event.comps[0].attrs.value
            if(errorStr && errorStr.length > 0){
              const data = { msg: '' }
              this.eventResultDisplay({ isSuccess: false, item:compareCompData, eventAttr: compareCompData.eventAttr, type:event.type, e:null, data, mouseBehavior:'' })
            }else{
              this.showToast('亲，没有次数了！！')
            }
            this.resetSubmitStatus()
            isContinue = false;
          }
        }
      }
      return isContinue;
    },
    getMainWbDataEventByEvents(events){
      let event_
      let tempArr = []
      _.forEach(events, (event) => {
        if(event.controlId && event.controlId.length > 0){
          tempArr.push(event)
        }
      })
      if(tempArr.length > 0){
        tempArr = _.sortBy(tempArr, (event) => { return event.index; });
        event_ = tempArr[0]
        //主事件是组件的第一个事件，是wblist值， controlId是组件的主事件id
      }
      return event_
    },
    async postPush(text, pic_ids, compId){
      let url = '/feact/wb_push'
      let params = { text, pic_ids }
      params.site_id = this.siteInfo.id
      params.com_id = compId
      let { data } = await axios_.post(url, params)
      if(data.code != 0){
        if (data.code == "900010"){
          if (this.$refs.login) {
            this.$refs.login.show();
          } else {
            this.$nextTick(function () {
              EventBus.$emit('login')
            })
          }
        }else{
          this.showToast(data.msg);
        }
      }else{
        this.showToast(data.msg);
      }
      let comType = "click"
      let apiUri = API_VERSION + url
      let wModule = "push"
      this.onPostStatics(null, { comType, wModule, jumpUrl: '', params: { pic_ids }, apiUri});
    },
    //在弹出弹层的时候可以获取之前的表单中设置的文本和图片在弹层中的动态文本和图片中显示
    showPopSetShareData(compIds) {
      let content = ''
      let url = ''
      if (compIds && compIds.length > 0) {
        let arr = compIds.split(",")
        _.forEach(arr, (compId) => {
          let relateCompId = compId
          if (relateCompId) {
            let componentData = this.componentMap[relateCompId];
            if (componentData.cid == COMPONENT_TYPES.wb_input) {
              content = this.formValues[relateCompId] && this.formValues[relateCompId].value
            } else if (componentData.cid == COMPONENT_TYPES.wb_img) {
              //页面中的动态图片，在弹层的动态图片中显示
              url = componentData.commonAttr.url
            } else if (componentData.cid == COMPONENT_TYPES.wb_radio) {
              url = this.formValues[relateCompId] && this.formValues[relateCompId].item.url
            }
          }
        })
        if (content && content.length > 0 || url && url.length > 0) {
          let shareData = { url };
          this.$store.commit('updateShareData', shareData);
        }
      }
    },
    randomPop(data){
      // {"allRange":[0,20],"range":["1,20","0"],"popId":[4,3]} 站点
      if(isJSON(data)){
        let randPopObj = JSON.parse(data);
        let ranges = randPopObj.range;
        let allRanges = randPopObj.allRange;
        if(!allRanges){
          allRanges = [0,5];
        }
        let popIds = randPopObj.popId;
        let random = _.random(allRanges[0], allRanges[1]);
        if(random == ranges[1]){
          this.showPop(popIds[1]);
        }else{
          this.showPop(popIds[0]);
        }
      }
    },
    relateCompPop(data){
      if(isJSON(data)){
        const relateCompPopObj = JSON.parse(data);
        const relateCompId = relateCompPopObj.relateCompId;
        const pops = relateCompPopObj.pops;
        const popIndex = this.formValues[relateCompId].value;
        const popId = pops[popIndex];
        this.showPop(popId);
      }
    },
    randomPage(pageStr){
      let pages = pageStr.split(',');
      let randomIndex = _.random(0, pages.length-1);
      let pageId = parseInt(pages[randomIndex]);
      return pageId;
    },
    relateCompPage(pageStr){
      const relateCompPageObj = JSON.parse(pageStr);
      const relateCompId = relateCompPageObj.relateCompId;
      const pages = relateCompPageObj.pages;
      const pageIndex = this.formValues[relateCompId].value;
      const pageId = pages[pageIndex];
      return pageId;
    },
    onFrontEvents(e, frontCommonEvents_) {
      //添加的普通事件 并行执行
      let commonEvents = frontCommonEvents_ ? frontCommonEvents_ : this.commonEvents
      let isContinue = false
      for(let i = 0, len = commonEvents.length; i < len; i++){
        const event = commonEvents[i];
        isContinue =  this.frontEvent({ event, e });
        if(isContinue) {
          //
        } else {
          break;
        }
      }
      if(frontCommonEvents_) {
        if(isContinue) {
          this.isPostWbEventOrCommonEvents({ loadEvent: null, e });
        }
      } else {
        this.resetSubmitStatus()
      }
      this.isEventPostFail = false;
    },
    frontEvent({ event, e }) {
      let popId
      let pageId
      let telOrMaiA_
      let isContinue = true
      let eventFunc
      switch (event.type) {
        case EVENT_HOVER_TYPES.animate.type:
          this.playAnimateOrGsap(e);
          break;
        case EVENT_HOVER_TYPES.openPush.type:
          eventFunc = new OpenPushEvent(event);
          eventFunc.excute({item: this.item, event, postPush: this.postPush});
          eventFunc.destroy();
          break;
        case EVENT_HOVER_TYPES.layerClose.type:
          EventBus.$emit('closePop')
          break
        case EVENT_HOVER_TYPES.link.type:
          if(event.comps[3] && event.comps[3].attrs.value) {
            const delayTime = event.comps[3] && event.comps[3].attrs.delayTime;
            window.setTimeout(() => {
              this.onEventLink(event);
            }, delayTime*1000)
          }else{
            this.onEventLink(event);
          }
          break
        case EVENT_HOVER_TYPES.shake.type:
          ShakeEvent.shakeEvent.excute({item:this.item, event});
          break
        case EVENT_HOVER_TYPES.scanQRCode.type:
          if(isWeibo() && window.wb){
            window.wb.scanQRCode((data) => {
              _.forEach(data, (value, key) => {
                alert("key: " + key + ", value: " + value);
              })
            });
          }
          break
        case EVENT_HOVER_TYPES.rotate3d.type:
          eventFunc = new Rotate3dEvent();
          eventFunc.excute({item:this.item, event, isPostWbEventOrCommonEvents: this.isPostWbEventOrCommonEvents})
          eventFunc.destroy();
          isContinue = false
          break
        case EVENT_HOVER_TYPES.interactionData.type:
          eventFunc = new InteractionDataEvent();
          eventFunc.excute({item:this.item, event});
          eventFunc.destroy();
          break
        case EVENT_HOVER_TYPES.compareInComps.type:
          eventFunc = new CompareInCompsEvent();
          isContinue = eventFunc.excute({item:this.item, event, resetSubmitStatus: this.resetSubmitStatus})
          if(isContinue) {
           //
          }else{
            this.resetSubmitStatus();
          }
          eventFunc.destroy();
          break
        case EVENT_HOVER_TYPES.frontEvents.type:
          eventFunc = new InteractionEvent();
          if(this.item){
            //组件
            isContinue = eventFunc.excute({
              item: this.item, event,
              interactionData: this.interactionData,
              clickItem: this.wbLists[this.commonAttr.itemIndex],
              isPostWbEventOrCommonEvents: this.isPostWbEventOrCommonEvents
            });
          }else{
            //页面
            isContinue = eventFunc.excute({item:this.item, event, interactionData: this.interactionData, clickItem: null});
          }
          // eventFunc.destroy();
          break
        case EVENT_HOVER_TYPES.showOrHide.type:
          eventFunc = new ShowOrHiddenEvent();
          eventFunc.excute({item:this.item, event});
          eventFunc.destroy();
          break
        case EVENT_HOVER_TYPES.layer.type:
          // popId = event.attrs.value.replace(/[^0-9]/ig, "") - 1
          popId = event.comps[0].attrs.value
          // 将表单中的数据传递到弹层中的动态文本或是动态图片中
          if (event.comps[1]) {
            this.showPopSetShareData(event.comps[1].attrs.value)
          }
          //随机弹层，设置弹层中的组件数据 1743 悦木之源
          if (!popId) {
            if(event.comps[2] && event.comps[2].attrs.value){
              this.randomPop(event.comps[2].attrs.value)
            }else if(event.comps[3] && event.comps[3].attrs.value){
              this.relateCompPop(event.comps[3].attrs.value);
            }
          }else{
            this.showPop(popId)
          }
          break
        case EVENT_HOVER_TYPES.dial.type:
          telOrMaiA_ = this.$el.getElementsByTagName("a")[0]
          if (telOrMaiA_) {
            telOrMaiA_.href = "tel:" + event.comps[0].attrs.value
          }
          break
        case EVENT_HOVER_TYPES.anchor.type:
          pageId = event.comps[0].attrs.value;
          if(pageId){
            this.showPage(pageId);
          }else if(event.comps[1].attrs.value || event.comps[2].attrs.value){
            let pageStr = event.comps[1].attrs.value;
            let relatePageStr = event.comps[2].attrs.value;
            if(relatePageStr && isJSON(relatePageStr)){
              //{"pages":[2,3,4,5,6],"relateCompId":"0c6a26d1-b303-48d7-a0d9-cb86e5ea474c"}
              pageId = this.relateCompPage(relatePageStr);
            }else if(pageStr){
              // 2,3,4,5,6 站点 2067
              pageId = this.randomPage(pageStr);
            }
            if(pageId){
              this.showPage(pageId);
            }
          }
          break
        case EVENT_HOVER_TYPES.email.type:
          telOrMaiA_ = this.$el.getElementsByTagName("a")[0]
          if (telOrMaiA_) {
            telOrMaiA_.href = "mailto:" + event.comps[0].attrs.value
          }
          break
        case EVENT_HOVER_TYPES.share.type:
          EventBus.$emit("share");
          break
        case EVENT_HOVER_TYPES.checkWeibo.type:
          // popId = event.attrs.value.replace(/[^0-9]/ig, "") - 1
          if (this.userInfo.uid) {
            pageId = event.comps[2].attrs.value
            if(pageId) {
              this.showPage(pageId);
            }
          } else {
            popId = event.comps[0].attrs.value
            if(popId){
              this.showPop(popId)
            }else if(event.comps[1].attrs.value == 'login'){
              EventBus.$emit('login')
            }
            isContinue = false
          }
          break;
        case EVENT_HOVER_TYPES.saveImg.type:
          // if(this.isLogin){
            if(this.isLoadJsObj.isMoveable){
              EventBus.$emit("exportSVG");
            }
            eventFunc = new SaveImgEvent();
            eventFunc.excute({item:this.item, event, isPostWbEventOrCommonEvents: this.isPostWbEventOrCommonEvents});
            isContinue = false;
          // }else{
          //   this.showAlert("请在微博中打开试试！！");
          // }
          break
        case EVENT_HOVER_TYPES.timer.type:
          EventBus.$emit("timerStart")
          break
        default:
          break
      }
      return isContinue;
      // let comType = "click"
      // let wModule = "click"
      // this.onPostStatics(e, { comType, wModule, jumpUrl });
    },
    showToast(msg) {
      //load事件不提示错误信息
      if(msg){
        Toast(msg);
      }
    },
    async post(url, params) {
      let e = params.e
      let item = params.item || this.item
      let type = params.type ? params.type : item.cid
      let mouseBehavior = params.mouseBehavior
      if (isHasOwnProperty(this.isApiSended, url)) {
        if (!this.isApiSended[url] && !this.isNotInterceptPost) {
          return
        }
      } else {
        this.isApiSended[url] = false
      }
      params.site_id = this.siteInfo.id
      let controlId = params.controlId
      let params_ = _.clone(params)
      delete params_.type
      delete params_.controlId
      delete params_.e
      delete params_.item
      delete params_.mouseBehavior

      this.eventIndex++
      let { data } = await axios_.post(url, params_)
      this.isApiSended[url] = true
      this.isPost = true
      let eventAttr = item.eventAttr

      // if(item.events && item.events.lottery){
      //   data.code = 0;
      //   data.data = {
      //     gift_id: 1,
      //     gift_idx: 0,
      //     gift_name: "王俊凯同款暴龙墨镜",
      //     pic_url: "https://static.hd.xxx.com/upload/biz/26/42219693_1372.png",
      //   }
      // }
      let isSuccess = false
      params.com_id = item.id
      if (data && data.code == 0) {
        isSuccess = true
        this.isEventPostFail = false;
        this.setStoreData({ type, params, item, data })
      } else {
        this.isEventPostFail = true;
        if (data.code == "900010" && (!params.ele_key || (params.ele_key && params.ele_key != GENERAL_TYPES_MAP.activity))) {
          if (this.$refs.login) {
            this.$refs.login.show();
          } else {
            this.$nextTick(() => {
              EventBus.$emit('login')
            })
          }
        }
      }
      //提示弹层会影响wbSubmitCallback事件，必须在提示信息eventResultDisplay这个之前执行
      if (type == EVENT_HOVER_TYPES.submit.type) {
        if (data.code == 0) {
          this.$store.commit("updateFormIsSubmit", false)
        }
        //回到btn组件继续执行剩下的事件
        EventBus.$emit("wbSubmitCallback", {e, compId: item.id});

        _.forEach(this.formValues, (item_) => {
          let item = item_.item;
          if(item){
            if(item.link && item.link.length > 0){
              this.openLinkBySelfUrl(item.link);
            }else if(item.pageId && this.pages[item.pageId]){
              this.showPage(parseInt(item.pageId))
            }else if(item.popId && this.pages[item.popId]){
              this.showPop(parseInt(item.popId))
            }
          }
        })
      }

       //微博插件事件 提示信息
       if (this.wbTypes.indexOf(params.type) != -1) {
        if (controlId == this.mainControlId) {
          this.eventResultDisplay({ isSuccess, item, eventAttr, type, e, data, mouseBehavior })
        }
      } else {
        //组件内部直接调用，或是表单提交 post
        if(type == EVENT_HOVER_TYPES.submit.type){
          if(item.events.submit.index == 0 || _.keys(item.events).length == 1){
            this.eventResultDisplay({ isSuccess, item, eventAttr, type, e, data, mouseBehavior })
          }
        }else{
          this.eventResultDisplay({ isSuccess, item, eventAttr, type, e, data, mouseBehavior })
        }
      }

      if (this.wbEvents[this.eventIndex]) {
        //继续执行下面的微博事件
        this.excuteNextWbEvent({type, isSuccess, e, code: data.code, eventAttr})
      }else {
        this.onFrontEvents(e)
        //触发页面加载事件 1911 每日签到
        if(eventAttr && isHasOwnProperty(eventAttr, "isEmitLoadEvent") && eventAttr.isEmitLoadEvent) {
          EventBus.$emit("reloadLoad", { pageId: this.pageIndex+1 });
        }
        if(eventAttr && isHasOwnProperty(eventAttr, "isEmitInitEvent") && eventAttr.isEmitInitEvent) {
          EventBus.$emit("reloadInit", { pageId: this.pageIndex+1 });
        }
      }

      //{comType, comId, pageIndex, apiType, apiUri, params, jumpUrl, clickSequence, mouseX, mouseY, debug}
      if(e){
        let interfaceType = url.split("/")[2]
        let wbPreArr = interfaceType && interfaceType.split("_")
        let wModule = wbPreArr ? wbPreArr[wbPreArr.length - 1] : ''
        let xy = getMousePos(e)
        delete params_.text
        postStatics(this.$store.state, {
          comType: 'post', comId: item.id, wModule, pageIndex: this.pageIndex, apiType: url.split("/")[1],
          apiUri: API_VERSION + url, params: params_, jumpUrl: "", clickSequence: "", mouseX: xy.x, mouseY: xy.y
        })
      }
    },
    //抽奖关联发博
    setPushCompPushIndex(itemIndex){
      let controlData = this.controls[this.item.id][CONTROL_TYPES.wb_lottery];
      if(controlData){
        let relateCompId = getCompIdByParam(controlData.data.relateCompId);
        if(relateCompId){
          let relateCompData = this.componentMap[relateCompId];
          relateCompData.commonAttr.itemIndex = itemIndex;
        }
      }
    },
    excuteNextWbEvent({isSuccess, e, eventAttr}){
      //抽奖失败就不能在减计数了，表单提交也不能执行
      if(isSuccess){
        this.postWbEvent({ e })
      }else{
        if(eventAttr.isBreak){
          this.onFrontEvents(e)
        }else{
          if(this.wbEvents[this.eventIndex]){
            this.postWbEvent({ e })
          }else{
            this.onFrontEvents(e)
          }
        }
      }
    },
    eventResultDisplay({ isSuccess, item, eventAttr, type, e, data, mouseBehavior }) {
      //在某些特殊事件中动态设置的字段，如果为true就不需要在这里在触发弹层了
      if (eventAttr && eventAttr.isNoActEventResult) {
        return
      }
      if (!eventAttr) {
        this.showToast(data.msg)
        return
      }
      if(item){
        this.postSetShareData({ isSuccess, item, type, data, eventAttr });
      }
      if(eventAttr.resultType == EVENTS_RESULTS_TYPES_MAP.page) {
        // 触发事件后 跳转页面
        let pageId;
        if(isSuccess) {
          pageId = eventAttr.successPanelId;
        }else {
          pageId = eventAttr.failPanelId;
        }
        if(pageId) {
          this.showPageCb = window.setInterval(() => {
            if(this.isClick) {
              this.showPage(pageId);
              window.clearInterval(this.showPageCb);
            }
          }, this.siteInfo.reloadTime)
        }
      } else if (eventAttr.resultType == EVENTS_RESULTS_TYPES_MAP.pop) {
        //老虎机的弹层需要在 动画结束后才能弹出
        if(this.item && this.item.cid == COMPONENT_TYPES.wb_slot_machine){
          let lotteryIndex = -1;
          if(isHasOwnProperty(this, 'lotteryIndex') && this.lotteryIndex >= 0){
            lotteryIndex = this.lotteryIndex;
          }
          this.delayShowPopParams = { isSuccess, item, eventAttr, type, data };
          EventBus.$emit('stopSlotMachine', { lotteryIndex });
          delete this.lotteryIndex;
        }else{
          this.postShowPop({ isSuccess, item, eventAttr, type, data });
        }
      } else if (eventAttr.resultType == EVENTS_RESULTS_TYPES_MAP.jump) {
        //触发事件后跳转
        if (isSuccess && eventAttr.link.length > 0) {
          this.openLinkBySelfUrl(eventAttr.link);
        }
      } else if (eventAttr.resultType == EVENTS_RESULTS_TYPES_MAP.component) {
        //一个组件只能走一次这个代码
        if (type == eventAttr.eventType) {
          //动态组件 在ui中直接显示结果
          let commonAttr = { isVisible: true }
          let compId
          if (isSuccess) {
            compId = eventAttr.successCompId
          } else {
            compId = eventAttr.failCompId
          }
          let relateCompId = getCompIdByParam(compId)
          let relateComp = relateCompId && this.componentMap[relateCompId]
          // 打组内元素需要进行处理
          let groupComp = relateComp && relateComp.isInGroup &&  this.componentMap[relateComp.groupCompId]
          if(groupComp && groupComp.cid == COMPONENT_TYPES.group_carousel){
            relateCompId = relateCompId + '_' + item.commonAttr.itemIndex + '_' + relateComp.commonAttr.qIndex;
          }
          let params = JSON.parse(eventAttr.params)
          if(params.delayTime){
            if(relateCompId){
              window.setTimeout(() => {
                this.$store.commit("updateComponentAttr", {id: relateCompId, commonAttr: { isVisible: false } })
              }, params.delayTime * 1000)
            }
          }else{
            this.$store.commit('resetVisibleComponents_')
          }
          if(relateCompId) {
            this.$store.commit('updateComponentVisible', { id: relateCompId, commonAttr })
          }else if(params.msg){
            this.showToast(params.msg)
          }
        }
        //load后执行 触发事件
        if (mouseBehavior === 'load') {
          this.isFail = false
          this.onEvent(e)
        }
      } else {
        //不提示任何信息
      }
    },
    isNextSubmitEvent(events, eventIndex){
      for(let i = 0, len = events.length; i < len; i++){
        if(i > eventIndex){
          if(events[i].type == EVENT_HOVER_TYPES.submit.type){
            return true;
          }
        }
      }
      return false;
    },
    onDelayShowPostPop(){
      if(this.delayShowPopParams){
        this.postShowPop(this.delayShowPopParams);
        delete this.delayShowPopParams;
      }
    },
    postShowPop({isSuccess, item, eventAttr, type, data}){
      let popId
      let content = data.msg;
      const infoStr = item.events[type] && item.events[type].comps[0].attrs.value
      if(LOTTERY_ERROR_NOS.indexOf(data.code) != -1){
        if(infoStr && infoStr.length > 0){
          const error = JSON.parse(infoStr);
          content = error[data.code];
        }
      }
      if (isSuccess) {
        popId = eventAttr.successPanelId
      } else {
        popId = eventAttr.failPanelId
        let isErrorParamsJson = eventAttr.params && isJSON(eventAttr.params)
        let customObj
        if(isErrorParamsJson) {
          //自定义参数{"errorCode":{"popId":6}}
          customObj = JSON.parse(eventAttr.params)
          if(isHasOwnProperty(customObj, data.code)) {
            if(customObj[data.code].popId && customObj[data.code].popId > 0) {
              popId = customObj[data.code].popId
            } else {
              popId = 0
              content = customObj[data.code]
            }
          } else if (isHasOwnProperty(customObj, "allRange")) {
            // 接口失败后按照 配置弹出弹，将组件中配置的自定义数据 复制给 shareData 2326
            if(this.item.interactionData) {
              let lists = this.item.interactionData.lists;
              let shareData = { content: '', url: ''};
              _.forEach(lists, (item) => {
                if(isJSON(item.params)) {
                  let obj = JSON.parse(item.params);
                  if(obj.videoUrl) {
                    shareData.videoUrl = obj.videoUrl;
                    shareData.posterUrl = item.url;
                  }
                } else {
                  shareData.url = item.url;
                }
              })
              this.$store.commit('updateShareData', shareData);
            }
            this.randomPop(eventAttr.params);
            return
          }
        }
      }
      if (popId > 0) {
        this.showPopCb = window.setInterval(() => {
          if(this.isClick){
            window.clearInterval(this.showPopCb)
            this.showPop(popId)
          }
        }, this.siteInfo.reloadTime)
      } else {
        this.showToast(content)
      }
    },
    postSetShareData({ isSuccess, item, type, data, eventAttr }){
      let shareData = { content: '', url: ''}
      let isSetShareData = false

      const infoStr = item.events[type] && item.events[type].comps[0].attrs.value
      if(LOTTERY_ERROR_NOS.indexOf(data.code) != -1) {
        if(infoStr && infoStr.length > 0){
          // {"code":"","default":""}
          const error = JSON.parse(infoStr)
          this.setShareUrlOrContent(error, data.code, shareData);
          isSetShareData = true
        }
      } else {
        const infoStr = item.events[type] && item.events[type].comps[0].attrs.value;
        //733  {"920105":"您已兑换过此礼品","920110":"您已兑换过此礼品","920117":"此礼物已兑换完","successText":"恭喜你兑换了$name$","failText":"兑换失败","default":"","notEnough":"碎片不足"}
        if(infoStr && infoStr.length > 0){
          const error = JSON.parse(infoStr)
          if(isSuccess){
            let attrName = this.getAttrNameByParam(error.successText);
            let controlData = this.getItemControls[CONTROL_TYPES.number];
            if(attrName && controlData){
              shareData.content = error.successText.replace("$num$", controlData.data.num);
            }else{
              shareData.content = error.successText;
            }
            //抽奖奖品
            if(type == EVENT_HOVER_TYPES.lottery.type){
              if (data.data.gift_name) {
                this.lotteryIndex = data.data.gift_idx;
                this.setPushCompPushIndex(data.data.gift_idx)
                shareData.content = error.successText ? error.successText.replace("$name$", data.data.gift_name) : data.data.gift_name;
                shareData.url = data.data.pic_url;
                this.setEveryRewrdPop({eventAttr, data});
              }else{
                this.staticsError(item, eventAttr, data);
              }
            }
          }else{
            this.setShareUrlOrContent(error, "notEnough", shareData);
          }
          isSetShareData = true
        }else{
          if(isSuccess && type == EVENT_HOVER_TYPES.lottery.type){
            if (data.data.gift_name) {
              this.lotteryIndex = data.data.gift_idx;
              this.setPushCompPushIndex(data.data.gift_idx);
              shareData.content = data.data.gift_name;
              shareData.url = data.data.pic_url;
              // 多维抽奖 2253 自定义数据
              if(item.interactionData && item.interactionData.isDimension && item.interactionData.dimensionLists){
                let list  = item.interactionData.dimensionLists[this.lotteryIndex]
                let index  = _.random(0, list.length - 1)
                shareData.url = list[index].url
              }
              this.setEveryRewrdPop({eventAttr, data, shareData})
              isSetShareData = true
            }else{
              this.staticsError(item, eventAttr, data);
            }
          }
        }
      }
      if(isSetShareData && (shareData.content || shareData.url)){
        this.$store.commit('updateShareData', shareData);
      }
    },
    staticsError(item, eventAttr, data){
      eventAttr.successPanelId = eventAttr.failPanelId;
      postStatics(this.$store.state, {
        comType: 'error', comId: item.id, wModule:'lottery', pageIndex: this.pageIndex, apiType: 'error',
        apiUri: '', params: JSON.stringify(data), jumpUrl: "", clickSequence: "", mouseX: 0, mouseY: 0
      })
    },
    setShareUrlOrContent(error, key, shareData){
      if(error[key]){
        const isImg = error[key].indexOf("http") != -1 ? true : false
        if(isImg){
          shareData.url = error[key]
        }else{
          if(error.failText && error.failText.indexOf("http") != -1){
            shareData.url = error.failText;
          }else{
            shareData.content = error[key];
          }
        }
      }else{
        if(error.failText && error.failText.indexOf("http") != -1){
          shareData.url = error.failText;
        }else{
          shareData.content = error[key];
        }
      }
    },
    setEveryRewrdPop({eventAttr, data}){
      //事件的成功弹层被具体的奖品需要特定的弹层替换
      let rewardControlData = this.getItemControls[CONTROL_TYPES.wb_lottery];
      let rewardItem = rewardControlData && rewardControlData.data.elements[data.data.gift_idx];
      if(rewardItem && rewardItem.popId > 0 && this.pops[rewardItem.popId-1]){
        if(eventAttr.resultType == EVENTS_RESULTS_TYPES_MAP.pop){
          eventAttr.successPanelId = rewardItem.popId;
        }
      }
    },
    setStoreData({ type, params, data }) {
      let controlId = params.controlId
      if (type == EVENT_HOVER_TYPES.number.type) {
        let data_ = { id: params.com_id, controlId, data: data.data }
        this.$store.commit('setWbNumber', data_)
      } else if (type == COMPONENT_TYPES.wb_share) {
        this.$store.commit('setShare', data)
      } else if (type == EVENT_HOVER_TYPES.vote.type) {
        let data_ = { id: params.com_id, controlId, data: data.data }
        this.$store.commit('setWbVoteNum', data_)
      } else if (type == 'uid') {
        // this.post("/feinit/userid", {item:{cid:"uid"}})
        //这个是点击登录按钮后回调，向后端请求uid
        this.$store.commit('setUserUid', data)
        postStatics(this.$store.state, {comType: "login", wModule: "login"})
      } else if (type == EVENT_HOVER_TYPES.judgeRightWrong.type) {
        let data_
        if (params.ele_key == GENERAL_TYPES_MAP.activity) {
          data_ = { id: params.com_id, controlId, data: data.data }
          this.$store.commit('updateInitGeneral', data_)
        } else if (params.ele_key == GENERAL_TYPES_MAP.gaobai) {
          data_ = { id: params.com_id, controlId, eles: data.data.ele, right: data.data.right, row: data.data.row }
          this.$store.commit('updateJudgeRightWrong', data_)
        }
      } else if (type == EVENT_HOVER_TYPES.activityInfo.type) {
        let data_ = { id: params.com_id, controlId, data: data.data }
        this.updateActivityInfo(data_)
      } else if (type == EVENT_HOVER_TYPES.general.type) {
        if(params.ele_key == GENERAL_TYPES_MAP.tree){
          let data_ = { id: params.com_id, controlId, data: _.merge({ isJoin: true }, data.data) }
          this.$store.commit('updateGeneral', data_)
        }
      } else if (type == EVENT_HOVER_TYPES.praise.type) {
        let data_ = { id: params.com_id, controlId, mid: params.mid }
        this.$store.commit('updateRepostsPraise', data_)
      } else if (type == EVENT_HOVER_TYPES.follow.type) {
        let data_ = { id: params.com_id, controlId, mid: params.mid }
        this.$store.commit('updateRepostsFollow', data_)
        let compData = this.componentMap[params.com_id];
        if(compData.cid == COMPONENT_TYPES.wb_btn) {
          let isNumber = !data.data;
          EventBus.$emit("refreshNumberDayExists", { compId: compData.id, isNumber });
        }
      }
    },
  },
}
